import router from "./router";
import store from "./store";
import {
    Message
} from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import {
    getAccessToken
} from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";
import {
    Refresh
} from "@/api/modules/user";
NProgress.configure({
    showSpinner: false,
}); // NProgress Configuration

const whiteList = ["/login"]; // no redirect whitelist

router.beforeEach(async(to, from, next) => {
    // start progress bar
    NProgress.start();

    // set page title
    document.title = getPageTitle(to.meta.title);

    // 如果是登录则不需要token校验
    if (to.path == '/login') {
        next()
        return
    }
    const accessToken = getAccessToken();
    console.log(accessToken);
    if (!accessToken) {
        try {

            const response = await Refresh();
            console.log("refreshData", response)
            if (response.status == 200) {
                // 刷新成功，重新设置AccessToken
                setAccessToken(response.data.AccessToken);
                next();
            } else {
                console.log("用户国企")
                    // 刷新失败或令牌过期，跳转到登录页面
                router.push("/login")
            }
        } catch (error) {
            // 刷新请求失败，跳转到登录页面
            console.log("error")
            router.push("/login")
        }
    } else {
        console.log("user", store.getters)
            // 有AccessToken，如果还未存储用户信息就获取用户信息
        if (!store.getters.userInfo)
            store.dispatch("user/GetUserInfo")
        next();
    }
});

router.afterEach(() => {
    // finish progress bar
    NProgress.done();
});